package xyz.lwm.lazycat.transaction.execute;

import java.util.Stack;

abstract class TransactionLocal {

    private static final ThreadLocal<Stack<Transaction>> transactionLocal = new ThreadLocal<>();

    static void setTransaction(Transaction tran) {
        initLocal();
        transactionLocal.get().push(tran);
    }

    static Transaction getTransaction() {
        if (hasContext()) {
            return transactionLocal.get().peek();
        }
        return null;
    }

    static void clearTransaction() {
        if (hasContext()) {
            transactionLocal.get().pop();
        }
        if (!hasContext()) {
            transactionLocal.remove();
        }
    }

    private static void initLocal() {
        if (transactionLocal.get() == null) {
            transactionLocal.set(new Stack<>());
        }
    }

    private static boolean hasContext() {
        Stack<Transaction> stack = transactionLocal.get();
        return stack != null && !stack.isEmpty();
    }

}
